import React, {
    useEffect,
    useRef,
    useState,
    useCallback,
    useMemo,
    forwardRef,
    useImperativeHandle,
} from 'react';
import api from 'api/config';
import './style.scss';
import classNames from 'classnames';
import VideoItem from './videoitem';
import ImageGrid from './empty';
import GradientBackground from './gradientbackground';
import DetailPop from '../detail-pop';
import Mockdata from '../../../../video_db.json';
import useVideoId from 'src/context/usevideoid';
import useFormStore from 'src/context/usetypeformstore';
import LazyImage from 'src/components/lazyimage';
import ButtonToolList from 'src/components/buttonlist';
import { toast } from 'react-toastify';
import FrameSequenceRender from 'src/components/framesequence';
import { use } from 'react';
import App from 'app';

const initialState = {
    image: {
        // video_type: 'text2video',
        version: '7',
        prompts: '',
        ratio: '9:16',
        bRefs: [],
        sRefs: [],
        uRefs: [],
        modelStyle: 0,
        isRaw: 0, //草图模式
        stylize: 0.5,
        particularity: 0.5,
        diversity: 0.5,
        speed: 1,
        resolution: 'high',
    },
    video: {
        // video_type: 'image2video',
        version: '7',
        prompts: '',
        firstFrame: '',
        lastFrame: '',
        isLoop: 0,
        onceGenerateNum: 4,
        motionSpeed: 'low',
        modelStyle: 'raw',
        resolution: 1,
    },
};

const VideoLibrary = forwardRef((props, ref) => {
    const { assetsURL } = App;

    const { videoId, videoSelectNum, setVideoId, setvideoSelectNum } =
        useVideoId();
    const { selectedType, setSelectedType, setFormData } = useFormStore();
    const tasklist = useFormStore().tasklist;
    const [videolist, setVideoList] = useState([]);
    const [selectedVideo, setSelectedVideo] = useState(0);
    const [showpop, setShowpop] = useState(false);

    const [datailData, setDetailData] = useState({});
    const [datailnum, setDetailNum] = useState();
    const [page, setPage] = useState(1);
    const [loading, setLoading] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const selectedTypeRef = useRef(selectedType);

    // 添加 ref
    const videoListRef = useRef(null);
    const videothumbnailRef = useRef(null);
    //为了loadvideo的时候获取到最新的值
    useEffect(() => {
        selectedTypeRef.current = selectedType;
    }, [selectedType]);
    useEffect(() => {
        if (videoListRef.current) {
            videoListRef.current.scrollTo({ top: 0, behavior: 'auto' });
        }
        setPage(1);
    }, [selectedType]);

    // 初始化 ref 数组

    const list = [
        {
            title: '图像创作',
            icon: (
                <svg
                    xmlns="http://www.w3.org/2000/svg"
                    xmlnsXlink="http://www.w3.org/1999/xlink"
                    fill="none"
                    version="1.1"
                    width="20"
                    height="20"
                    viewBox="0 0 20 20"
                >
                    <defs>
                        <clipPath id="master_svg0_444_63058/444_07276">
                            <rect x="20" y="0" width="20" height="20" rx="0" />
                        </clipPath>
                    </defs>
                    <g>
                        <g
                            transform="matrix(-1,0,0,1,40,0)"
                            clipPath="url(#master_svg0_444_63058/444_07276)"
                        >
                            <g>
                                <path
                                    d="M23.25,3.375L36.75,3.375C37.4404,3.375,38,3.934644,38,4.625L38,15.375C38,15.8591,37.7248,16.2789,37.3223,16.4866C37.2656,16.5208,37.2063,16.5509,37.1443,16.5771C36.9704,16.6507,36.7885,16.6875,36.5987,16.6875L23.40131,16.6875C23.21152,16.6875,23.02964,16.6507,22.855663,16.5771C22.793669,16.5509,22.73432,16.520699999999998,22.677607,16.4866C22.275162,16.2789,22,15.8591,22,15.375L22,4.625C22,3.934644,22.559643,3.375,23.25,3.375ZM36.75,4.625L23.25,4.625L23.25,12.41219L26.06464,9.597529999999999C26.27916,9.383009999999999,26.61675,9.35353,26.86521,9.52761L29.472,11.354L32.2453,8.44383C32.4834,8.193950000000001,32.879,8.18441,33.1289,8.42254C33.1382,8.43145,33.1473,8.44065,33.1561,8.45013L36.75,12.32738L36.75,4.625ZM27.8125,7.5C27.8125,7.3307400000000005,27.84533,7.16849,27.910989999999998,7.01325C27.97428,6.863630000000001,28.06349,6.73126,28.17862,6.6161200000000004C28.29375,6.50099,28.42613,6.41178,28.57575,6.34849C28.731,6.282830000000001,28.893250000000002,6.25,29.0625,6.25C29.231749999999998,6.25,29.394,6.282830000000001,29.54925,6.34849C29.69888,6.41178,29.83125,6.50099,29.94637,6.6161200000000004C30.061500000000002,6.73126,30.150750000000002,6.863630000000001,30.214,7.01325C30.27967,7.16849,30.3125,7.3307400000000005,30.3125,7.5C30.3125,7.66926,30.27967,7.83151,30.214,7.98675C30.150750000000002,8.13637,30.061500000000002,8.26875,29.94637,8.383880000000001C29.83125,8.49901,29.69888,8.58823,29.54925,8.65151C29.394,8.71717,29.231749999999998,8.75,29.0625,8.75C28.893250000000002,8.75,28.731,8.71717,28.57575,8.65151C28.42612,8.58823,28.29375,8.49901,28.17862,8.383880000000001C28.06349,8.26875,27.97428,8.13637,27.910989999999998,7.98675C27.84533,7.83151,27.8125,7.66926,27.8125,7.5Z"
                                    fill="#FAFAFC"
                                    fillOpacity="1"
                                />
                            </g>
                        </g>
                    </g>
                </svg>
            ),
            type: 'image',
            bg: 'https://img.alicdn.com/imgextra/i1/O1CN01H8lQCZ1lcJea99pTj_!!6000000004839-2-tps-1260-220.png',
        },
        {
            title: '视频创作',
            icon: (
                <svg
                    xmlns="http://www.w3.org/2000/svg"
                    xmlnsXlink="http://www.w3.org/1999/xlink"
                    fill="none"
                    version="1.1"
                    width="20"
                    height="20"
                    viewBox="0 0 20 20"
                >
                    <g>
                        <g>
                            <path
                                d="M17.75,5.5L17.75,14.5C17.75,14.7541,17.7008,14.9974,17.6024,15.23C17.5075,15.4544,17.3736,15.653,17.2008,15.8258C17.028,15.9986,16.8294,16.1325,16.605,16.2274C16.3724,16.3258,16.1291,16.375,15.875,16.375L4.125,16.375C3.87097,16.375,3.6276200000000003,16.3258,3.39497,16.2274C3.17058,16.1325,2.97198,15.9986,2.79917,15.8258C2.62637,15.653,2.4925100000000002,15.4544,2.3976,15.23C2.2992,14.9974,2.2499999701977,14.7541,2.2499999701977,14.5L2.2499999701977,5.5C2.2499999701977,5.24597,2.2992,5.00262,2.3976,4.76997C2.4925100000000002,4.54558,2.62637,4.34698,2.79917,4.17417C2.97197,4.00137,3.17057,3.8675100000000002,3.39497,3.7726C3.6276200000000003,3.6742,3.87097,3.6249999701977,4.125,3.6249999701977L15.875,3.6249999701977C16.1291,3.6249999701977,16.3724,3.6742,16.605,3.7726C16.8294,3.8675100000000002,17.028,4.00137,17.2008,4.17417C17.3736,4.34697,17.5075,4.54557,17.6024,4.76997C17.7008,5.00262,17.75,5.24597,17.75,5.5ZM16.4511,14.7431C16.4837,14.6661,16.5,14.5851,16.5,14.5L16.5,5.5C16.5,5.41495,16.4837,5.33392,16.4511,5.2569099999999995C16.4195,5.1822099999999995,16.3748,5.1159300000000005,16.3169,5.05806C16.259,5.00019,16.1928,4.95545,16.1181,4.9238599999999995C16.0411,4.89129,15.9601,4.875,15.875,4.875L4.125,4.875C4.03995,4.875,3.95892,4.89129,3.88191,4.9238599999999995C3.80721,4.95545,3.74093,5.00019,3.6830600000000002,5.05806C3.62519,5.1159300000000005,3.58045,5.18222,3.54886,5.2569099999999995C3.5162899999999997,5.33392,3.5,5.41495,3.5,5.5L3.5,14.5C3.5,14.5851,3.5162899999999997,14.6661,3.54886,14.7431C3.58045,14.8178,3.62519,14.884,3.6830600000000002,14.9419C3.74093,14.9998,3.80721,15.0445,3.88191,15.0761C3.95892,15.1087,4.03995,15.125,4.125,15.125L15.875,15.125C15.9601,15.125,16.0411,15.1087,16.1181,15.0761C16.1928,15.0445,16.259,14.9998,16.3169,14.9419C16.3748,14.884,16.4195,14.8178,16.4511,14.7431ZM7.78125,11.67793L7.78125,8.32208C7.78125,7.8755,8.0195,7.46284,8.40625,7.2395499999999995C8.793,7.01626,9.2695,7.01626,9.65625,7.2395499999999995L12.5625,8.91747C12.9493,9.14077,13.1875,9.55342,13.1875,10.00001C13.1875,10.44659,12.9493,10.85925,12.5625,11.08254L9.65625,12.76046C9.2695,12.98375,8.793,12.98375,8.40625,12.76046C8.0195,12.53717,7.78125,12.12451,7.78125,11.67793ZM9.03125,8.32208L9.03125,11.67793L11.9375,10.00001L9.03125,8.32208Z"
                                fill="#FAFAFC"
                                fillOpacity="1"
                            />
                        </g>
                    </g>
                </svg>
            ),
            type: 'video',
            bg: 'https://img.alicdn.com/imgextra/i1/O1CN01y3aYDw1eqKSdqpy6H_!!6000000003922-2-tps-1260-220.png',
        },
    ];

    async function loadVideo(page = 1) {
        // console.log(selectedType, 'loadVideoselectedType');
        try {
            const currentSelectedType = selectedTypeRef.current;
            const response = await api.post('/v1/tob/jobs', {
                type: selectedType,
                pageSize: 10,
                pageNumber: page,
                filter_failed: selectedType == 'all' ? 1 : 0,
            });
            if (currentSelectedType !== selectedType) {
                console.log('类型已更改，忽略此次响应');
                return;
            }

            if (page > 1) {
                setVideoList((prevVideoList) => {
                    const newList = [...prevVideoList, ...response.data.list];

                    return newList;
                });
                setLoading(false);

                if (response.data.list.length < 10) {
                    setHasMore(false);
                }
            } else {
                setVideoList(response.data.list);
                setHasMore(response.data.list.length > 10); // 重置 hasMore 状态
            }
        } catch (error) {}
    }
    useEffect(() => {
        loadVideo();
    }, [selectedType]);

    // 使用 useCallback 优化点击处理函数
    const handleFilterClick = useCallback((type) => {
        setSelectedType(type);
    }, []);

    const handlepop = useCallback((item, num) => {
        setShowpop(true);
        setDetailData(item);
        setDetailNum(num);
    }, []);

    const handlepopclose = useCallback(() => {
        setShowpop(false);
        setVideoId('');
        setvideoSelectNum('');
    }, [setVideoId, setvideoSelectNum]);

    //每次点击生成时先生成一个假数据
    const addFake = (data, type) => {
        data.type = type;
        setVideoList((prevList) => [data, ...prevList]);
        setFormData(type, initialState[type]);
        //开始轮询
        pollJobStatus(data.jobId);
    };

    useImperativeHandle(ref, () => ({
        addFake,
    }));

    const handleScroll = useCallback(
        (ref) => {
            if (loading || !hasMore) return;
            if (ref.current) {
                const { scrollTop, scrollHeight, clientHeight } = ref.current;
                // 检查是否接近底部（这里设置了50px的缓冲区）
                if (scrollTop + clientHeight >= scrollHeight - 1000) {
                    setLoading(true); // 开始加载
                    setPage((prevPage) => prevPage + 1); // 加载下一页的数据
                }
            }
        },
        [loading, hasMore, ref]
    );
    useEffect(() => {
        if (page > 1 && hasMore && loading) {
            loadVideo(page);
        }
    }, [page, hasMore, loading]);

    const pollJobStatus = async (jobId) => {
        const pollInterval = setInterval(async () => {
            try {
                const response = await api.get(`/v1/tob/job/${jobId}`);
                const jobData = response.data;

                switch (jobData.job_status) {
                    case 1:
                        break;
                    case 2:
                        clearInterval(pollInterval);
                        await loadVideo();
                        break;
                    case 3:
                        // 生成失败也立刻显示
                        toast.error(`操作失败！${jobData.response.comment}`, {
                            autoClose: 3000, // 自动关闭时间（毫秒）
                            hideProgressBar: true,
                        });
                        clearInterval(pollInterval);
                        await loadVideo();
                        break;
                }
            } catch (error) {
                console.error(`查询任务 ${jobId} 状态失败:`, error);
                clearInterval(pollInterval);
            }
        }, 3000);
    };

    return (
        <div className="video-library">
            {selectedType == 'all' && (
                <div className="library-top">
                    <p className="library-top-title">
                        <span>Hi！</span>你今天想创作什么？
                        <img
                            className="top-right-logo"
                            src="https://img.alicdn.com/imgextra/i4/O1CN01CiczIJ1mQEpCv71mq_!!6000000004948-2-tps-180-85.png"
                            alt=""
                        />
                    </p>

                    <div className="library-top-select-line">
                        {list.map((item, index) => {
                            return (
                                <div
                                    className="library-top-select-line-item"
                                    key={index}
                                    onClick={() => {
                                        setSelectedType(item.type);
                                    }}
                                >
                                    {/* {item.icon} */}

                                    <div className="bg">
                                        <FrameSequenceRender
                                            frameLength={151} // 总帧数
                                            frameUrl={`${assetsURL}images/banner${
                                                index + 1
                                            }/banner${index + 1}_`} // 帧图片基础URL
                                            frameSuffix="png" // 图片后缀
                                            hoverStartFrame={0} // 悬停开始帧
                                        >
                                            <p className="library-top-select-line-item-title">
                                                {item.title}
                                            </p>
                                            <div className="arrow-item">
                                                <p>立即创作</p>
                                                <svg
                                                    xmlns="http://www.w3.org/2000/svg"
                                                    xmlnsXlink="http://www.w3.org/1999/xlink"
                                                    fill="none"
                                                    version="1.1"
                                                    width="20"
                                                    height="20"
                                                    viewBox="0 0 20 20"
                                                >
                                                    <g transform="matrix(-1,0,0,1,40,0)">
                                                        <g>
                                                            <path
                                                                d="M35.5,9.375C35.8452,9.375,36.125,9.65483,36.125,10C36.125,10.34518,35.8452,10.625,35.5,10.625L26.25888,10.625L30.19194,14.5581C30.30915,14.6753,30.375,14.8342,30.375,15C30.375,15.1658,30.30915,15.3247,30.19194,15.4419C30.07473,15.5592,29.91576,15.625,29.75,15.625C29.58424,15.625,29.42527,15.5592,29.30806,15.4419L24.30806,10.441939999999999C24.0639797,10.19786,24.0639797,9.80214,24.30806,9.558060000000001L29.30806,4.55806C29.42527,4.4408502,29.58424,4.375000163913,29.75,4.375000163913C29.91576,4.375000163913,30.07473,4.4408502,30.19194,4.55806C30.30915,4.67527,30.375,4.83424,30.375,5C30.375,5.16576,30.30915,5.32473,30.19194,5.44194L26.25888,9.375L35.5,9.375Z"
                                                                fill="#FFFFFF"
                                                                fillOpacity="1"
                                                            />
                                                        </g>
                                                    </g>
                                                </svg>
                                            </div>
                                        </FrameSequenceRender>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                    <div className="library-history-title-filter-buttons">
                        <p className="library-history-title">创作历史</p>
                        <div className="filter-buttons">
                            <div
                                className={classNames('filter-button', {
                                    active: selectedType == 'all',
                                })}
                                onClick={() => handleFilterClick('all')}
                                key="selectedType"
                            >
                                全部
                            </div>
                            <div
                                className={classNames('filter-button', {
                                    active: selectedType == 'image',
                                })}
                                key="image"
                                onClick={() => handleFilterClick('image')}
                            >
                                图片生成
                            </div>
                            <div
                                className={classNames('filter-button', {
                                    active: selectedType == 'video',
                                })}
                                key="video"
                                onClick={() => handleFilterClick('video')}
                            >
                                视频生成
                            </div>
                        </div>
                    </div>

                    {selectedType === 'all' &&
                        (videolist.length > 0 ? (
                            <div
                                className="video-library-thumbnail"
                                ref={videothumbnailRef}
                                onScroll={() => {
                                    handleScroll(videothumbnailRef);
                                }}
                            >
                                {videolist.map((item, index) => {
                                    // const item = video.params;
                                    return (
                                        <React.Fragment
                                            key={item.jobId || index}
                                        >
                                            {item.type === 'image' &&
                                                item.status === 2 &&
                                                item.resultUrl.map(
                                                    (sitem, sindex) => {
                                                        return (
                                                            <div
                                                                className={`video-library-thumbnail-item `}
                                                                key={`${index}-${sindex}`}
                                                                onClick={() => {
                                                                    handlepop(
                                                                        item,
                                                                        sindex
                                                                    );
                                                                }}
                                                            >
                                                                <LazyImage
                                                                    ratio={
                                                                        'horizontal'
                                                                    }
                                                                    src={sitem}
                                                                    alt=""
                                                                />
                                                                <ButtonToolList
                                                                    data={item}
                                                                    imageUrl={
                                                                        item
                                                                            .resultUrl[
                                                                            sindex
                                                                        ]
                                                                    }
                                                                    index={
                                                                        sindex
                                                                    }
                                                                    loadVideo={
                                                                        loadVideo
                                                                    }
                                                                ></ButtonToolList>
                                                            </div>
                                                        );
                                                    }
                                                )}
                                            {item.type === 'video' &&
                                                item.status === 2 &&
                                                item.resultUrl?.map(
                                                    (sitem, sindex) => {
                                                        return (
                                                            <div
                                                                className="video-library-thumbnail-item"
                                                                key={`${index}-${sindex}`}
                                                                onClick={() => {
                                                                    handlepop(
                                                                        item,
                                                                        sindex
                                                                    );
                                                                }}
                                                            >
                                                                <LazyImage
                                                                    ratio={
                                                                        'horizontal'
                                                                    }
                                                                    src={
                                                                        item
                                                                            .params
                                                                            .firstFrame ||
                                                                        'https://img.alicdn.com/imgextra/i2/O1CN01QTtdhg1dyk7M2C4e4_!!6000000003805-2-tps-13-14.png'
                                                                    }
                                                                    alt=""
                                                                />
                                                                <img
                                                                    className="play-icon"
                                                                    src="https://img.alicdn.com/imgextra/i1/O1CN01WdLEYq29v8i7cy4ti_!!6000000008129-2-tps-24-24.png"
                                                                    alt=""
                                                                />
                                                                <ButtonToolList
                                                                    data={item}
                                                                    imageUrl={
                                                                        item
                                                                            .resultUrl[
                                                                            sindex
                                                                        ]
                                                                    }
                                                                    index={
                                                                        sindex
                                                                    }
                                                                    loadVideo={
                                                                        loadVideo
                                                                    }
                                                                ></ButtonToolList>
                                                            </div>
                                                        );
                                                    }
                                                )}
                                        </React.Fragment>
                                    );
                                })}
                            </div>
                        ) : (
                            <div className="video-library-empty">
                                <ImageGrid></ImageGrid>
                            </div>
                        ))}
                </div>
            )}

            {selectedType != 'all' && (
                <>
                    {videolist.length > 0 && (
                        <div className="video-library-content">
                            <div
                                className="video-library-list"
                                ref={videoListRef}
                                onScroll={() => {
                                    handleScroll(videoListRef);
                                }}
                            >
                                {videolist.map((item, index) => {
                                    return (
                                        <VideoItem
                                            item={item}
                                            index={index}
                                            key={`${item.jobId}-${index}`}
                                            handlepop={handlepop}
                                            loadVideo={loadVideo}
                                            addfake={(data, type) => {
                                                addFake(data, type);
                                            }}
                                        ></VideoItem>
                                    );
                                })}
                            </div>
                        </div>
                    )}
                    {videolist.length == 0 && (
                        <div className="video-library-empty">
                            <ImageGrid></ImageGrid>
                        </div>
                    )}
                </>
            )}

            {showpop && (
                <DetailPop
                    handlepopclose={handlepopclose}
                    data={datailData}
                    num={datailnum}
                    videolist={videolist}
                    addfake={(data, type) => {
                        addFake(data, type);
                    }}
                    loadVideo={loadVideo}
                ></DetailPop>
            )}
        </div>
    );
});

export default VideoLibrary;
